package cn.lijiguo.concurrency.part1.ch06;

/**
 * RightWayStopThreadWithoutSleep
 *
 * 正确的方式停止线程（run 方法中没有调用 sleep 或者 wait 方法时停止线程）
 *
 * @author lijiguo
 * @date 2020/1/6 10:44
 */
public class RightWayStopThreadWithoutSleep implements Runnable {

    public static void main(String[] args) {
        Thread t1 = new Thread(new RightWayStopThreadWithoutSleep(), "t1");
        // 启动线程
        t1.start();

        // 线程睡眠 1s
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 中断线程
        t1.interrupt();
    }

    @Override
    public void run() {
        int num = 0;
        while (num <= Integer.MAX_VALUE / 2) {
            // 判断线程是否响应中断
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("-----> 线程即将停止。。。");
                break;
            }
            if (num % 10000 == 0) {
                System.out.println(num + " 是 10000 的倍数");
            }

            num++;
        }

        System.out.println("------> 任务运行结束了。。。");
    }
}
